//
//  PPPhotoBrowserController.m
//  pickpic
//
//  Created by 胡文广 on 2017/4/11.
//  Copyright © 2017年 MicroDream. All rights reserved.
//

#import "PPPhotoBrowserController.h"
#import "PPAbstractViewController.h"
#import "PPAlbumImageModel.h"
#import "PPPhoto.h"
#import "PPBrowserView.h"
#import "PPEbookPreviewViewController.h"
#import "PPEbookPreviewCollectionViewController.h"

#import "PPTemplateModel.h"
#import "PPNavBarPreview.h"
#import "PPHomeAlbumModel.h"
#import "PPTemplateInnerModel.h"
#import "PPMaskView.h"
#import "PPTemplateCoverFrame.h"
#import "PPHomeEbookModel.h"
#import "PPMusicListViewController.h"
#import "JCDownloadOperation.h"
#import <AVFoundation/AVFoundation.h>
#define kPreviewChange @"PreviewChange"
@interface PPPhotoBrowserController ()<PPEbookPreviewViewControllerDelegate,PPEbookPreviewCollectionViewControllerDelegate>
@property (nonatomic,strong) PPNavBarPreview *navBarPreview;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,assign) BOOL isHidden;
@property (nonatomic,strong) PPEbookPreviewViewController *previewVc;
@property (nonatomic,strong) PPEbookPreviewCollectionViewController *collectionVc;
@property (nonatomic,strong) UIViewController *currentVc;
@property (nonatomic,strong) NSMutableArray *items;
@property (nonatomic,strong) PPMaskView *maskView;

@property (nonatomic,strong) NSMutableArray *collectionImgs;

//记录最后一次放大的图片
@property (nonatomic,assign) NSInteger previousSelectIndex;


@property (nonatomic,strong) NSMutableArray *pics;

@property (nonatomic,strong) UIButton *moreBtn;
@property (nonatomic,strong) UIButton *songBtn;

@property (nonatomic,strong) JCDownloadOperation *operation;

//@property (nonatomic,strong) AVPlayerLayer *playerLayer;
//@property (nonatomic,strong) AVPlayer *player;

@property (nonatomic,copy) NSString *playURL;


@property (nonatomic,strong)  AVAudioPlayer* audioPlayer;
@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,assign) BOOL isShowSongBtn;
@end

@implementation PPPhotoBrowserController

- (void)viewWillDisappear:(BOOL)animated{

    [super viewWillDisappear:animated];
    
    self.moreBtn.hidden = YES;
    self.songBtn.hidden = YES;

}
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.moreBtn.hidden = NO;
    self.songBtn.hidden = NO;
}

- (UIButton *)moreBtn{

    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_moreBtn setImage:[UIImage imageNamed:@"ebook_more"] forState:UIControlStateNormal];
        _moreBtn.layer.masksToBounds = YES;
        _moreBtn.layer.cornerRadius = 3;
        [_moreBtn addTarget:self action:@selector(clickMore) forControlEvents:UIControlEventTouchUpInside];
    }
    return _moreBtn;
}
- (UIButton *)songBtn{
    
    if (!_songBtn) {
        _songBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_songBtn setImage:[UIImage imageNamed:@"song_pause"] forState:UIControlStateNormal];
        _songBtn.layer.masksToBounds = YES;
        _songBtn.layer.cornerRadius = 15;
//         [_songBtn setImage:[UIImage imageNamed:@"song_play"] forState:UIControlStateSelected];
        [_songBtn addTarget:self action:@selector(clickPlayMusic:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _songBtn;
}
- (NSMutableArray *)pics{

    if (!_pics) {
        _pics = [NSMutableArray array];
    }
    return _pics;
}

- (NSMutableArray *)collectionImgs{

    if (!_collectionImgs) {
        
        _collectionImgs = [NSMutableArray array];
    }
    return _collectionImgs;
}
- (PPMaskView *)maskView{

    if (!_maskView) {
        _maskView = [[PPMaskView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    }
    return _maskView;
}


- (UILabel *)titleLabel{

    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.frame = CGRectMake(0, 0, SCREEN_WIDTH, 44);
        _titleLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLabel;
}
- (PPNavBarPreview *)navBarPreview{

    if (!_navBarPreview) {
        _navBarPreview = [[PPNavBarPreview alloc] init];
        _navBarPreview.frame = CGRectMake(0, 0,SCREEN_WIDTH, 44);
    }
    return _navBarPreview;
}
- (NSMutableArray *)items{

    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}
- (PPEbookPreviewViewController *)previewVc{

    if (!_previewVc) {
        _previewVc = [[PPEbookPreviewViewController alloc] init];
        _previewVc.delegate = self;
    }
    return _previewVc;
}
- (PPEbookPreviewCollectionViewController *)collectionVc{

    if (!_collectionVc) {
        _collectionVc = [[PPEbookPreviewCollectionViewController alloc] init];
        _collectionVc.delegate = self;
    }
    return _collectionVc;
}
#pragma mark - 生命周期方法
- (void)hiddenSubviews{

    
}
- (void)showSubViews{


}
- (void)popViewPreviousController{
    
    if (self.currentVc == self.collectionVc) {
        self.moreBtn.hidden = NO;
        self.songBtn.hidden = NO;
        if (self.previewVc == nil) {
            self.previewVc.changeSize = (self.type == PPPhotoBrowserTypeEbook);
            [self addChildViewController:self.previewVc];
        }
        self.previewVc.photos = self.items;
        self.previewVc.isPreviewFullScreen = (self.type == PPPhotoBrowserTypeTemplate || self.type == PPPhotoBrowserTypeEbook||self.type == PPPhotoBrowserTypeAlbumNone);
        self.previewVc.changeSize = (self.type == PPPhotoBrowserTypeEbook);
        self.previewVc.currentIndex = self.previousSelectIndex;
         self.previewVc.normalStyle = self.type == PPPhotoBrowserTypeAlbumNone;
        if (self.templateM.orderNum == 0) {
            self.previewVc.normalStyle = YES;
        }
        
        [self.collectionVc.view removeFromSuperview];
        [self.collectionVc removeFromParentViewController];
         self.previewVc.pictures = self.pics;
        self.previewVc.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        
        [self.view addSubview:self.previewVc.view];
        self.currentVc = self.previewVc;
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_more"] style:UIBarButtonItemStylePlain target:self action:@selector(clickMore)];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"音乐" style:UIBarButtonItemStyleDone target:self action:@selector(goMusicList)];
        self.navigationItem.rightBarButtonItem.tintColor = BLACK;
        [self.previewVc showPhotoDescIndex:0];
    }else{
        if (self.BlockSaveEbookInfo && [[[NSUserDefaults standardUserDefaults] objectForKey:@"editOperation"] boolValue]) {
            self.BlockSaveEbookInfo();
        }
        
        
        [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"editOperation"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        
        [self.moreBtn removeFromSuperview];
        self.moreBtn = nil;
        
        [self.songBtn removeFromSuperview];
        self.songBtn = nil;
        
        [self.audioPlayer stop];
        
        [self stop];
        
        [super popViewPreviousController];
    }
}

- (void)dealloc{
    [self stop];
//    [self.playerLayer removeFromSuperlayer];
//    self.playerLayer = nil;
    
    [[NSUserDefaults standardUserDefaults] setBool:FALSE forKey:@"editOperation"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    self.songBtn.frame = CGRectMake(SCREEN_WIDTH - 45,80, 30, 30);

}
- (void)goMusicList{

    PPMusicListViewController *musicList = [[PPMusicListViewController alloc] init];
    musicList.albumHomeModel = self.albumHomeModel;
    musicList.musicURL = self.playURL;
    musicList.BlockBindSuccess = ^(NSString *musicPlayPath) {
        
//        if (!self.songBtn) {
            [self.navigationController.view addSubview:self.songBtn];
//        }
        
        [self stop];
        
        self.songBtn.selected = YES;
        
        [self musicPlayerWithPath:musicPlayPath];
        
    };
    
    
    musicList.BlockDeleteBindSuccess = ^{
        
        
        [self stop];
        
        self.songBtn.selected = NO;
        
        [self.songBtn removeFromSuperview];
        
        self.songBtn = nil;
        
    };
    [self.navigationController pushViewController:musicList animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.previousSelectIndex = 0;
    self.view.backgroundColor = WHITE;
    if (self.type == PPPhotoBrowserTypeTemplate) {
        
        self.title = self.templateM.title;
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
        self.navigationItem.leftBarButtonItem.tintColor = BLACK;
        
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:(self.templateM.downloadType == PPTemplateDownLoadTypeFinish||self.templateM.downloadType == PPTemplateDownLoadTypeEmploy)?@"使用":@"下载" style:UIBarButtonItemStylePlain target:self action:@selector(downTemplate:)];
        
        //模板样式预览
        for (NSString *url in self.templateM.previewUrls) {
            PPPhoto *photo = [[PPPhoto alloc] init];
            photo.bigImgUrl = url;
            [self.items addObject:photo];
        }
        
        [self showBrowserView];
    }else if (self.type == PPPhotoBrowserTypeAlbumNone){
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
        self.navigationItem.leftBarButtonItem.tintColor = BLACK;
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_more"] style:UIBarButtonItemStylePlain target:self action:@selector(clickMore)];
//        self.navigationItem.rightBarButtonItem.tintColor = BLACK;
        //默认模板
        [self reloadData];
        
//        self.moreBtn.frame = CGRectMake(SCREEN_WIDTH - 55, SCREEN_HEIGHT - 70, 50, 50);
//        [self.navigationController.view addSubview:self.moreBtn];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"音乐" style:UIBarButtonItemStyleDone target:self action:@selector(goMusicList)];
        self.moreBtn.frame = CGRectMake(SCREEN_WIDTH - 45, SCREEN_HEIGHT - 75, 30, 30);
        [self.navigationController.view addSubview:self.moreBtn];
        
        self.navigationItem.rightBarButtonItem.tintColor = BLACK;
        self.songBtn.frame = CGRectMake(SCREEN_WIDTH - 45,80, 30, 30);
        [self.navigationController.view addSubview:self.songBtn];
        
        self.songBtn.enabled = NO;
        
        [self clickPlayMusic:self.songBtn];
    }else if (self.type == PPPhotoBrowserTypeEbook){
        
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_back"] style:UIBarButtonItemStylePlain target:self action:@selector(popViewPreviousController)];
        self.navigationItem.leftBarButtonItem.tintColor = BLACK;
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_more"] style:UIBarButtonItemStylePlain target:self action:@selector(clickMore)];
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"音乐" style:UIBarButtonItemStyleDone target:self action:@selector(goMusicList)];
        
        self.navigationItem.rightBarButtonItem.tintColor = BLACK;
//        生成电子书 ->设置背景图（封面底图+描述+内页+封底底图）->添加数据
//        [self reloadData];
        
        [self reloadEbookData];

        self.moreBtn.frame = CGRectMake(SCREEN_WIDTH - 45, SCREEN_HEIGHT - 75, 30, 30);
        [self.navigationController.view addSubview:self.moreBtn];
       
        
        self.songBtn.frame = CGRectMake(SCREEN_WIDTH - 45,80, 30, 30);
        [self.navigationController.view addSubview:self.songBtn];
        self.songBtn.enabled = NO;
        [self clickPlayMusic:self.songBtn];
        
//        BOOL isPath = [[[NSUserDefaults standardUserDefaults] objectForKey:kPreviewChange] boolValue];
//        if (!isPath) {
//            UIWindow *window = [[UIApplication sharedApplication].windows lastObject];
//            self.maskView.rec = CGRectMake(self.templateM.coverFrameM.boxXaxis, self.templateM.coverFrameM.boxYaxis+64, self.templateM.coverFrameM.boxWidth, self.templateM.coverFrameM.boxHeight);
//            [self.maskView show];
//            [window addSubview:self.maskView];
//            
//            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kPreviewChange];
//            [[NSUserDefaults standardUserDefaults] synchronize];
//        }
        
    }
    if (IS_IOS_8) {
        
        [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PFFontBold(16)} forState:UIControlStateNormal];
    }else{
        
                [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:PPFONT(PFBold, 16)} forState:UIControlStateNormal];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTitle:) name:PPAlbumChanageTitle object:nil];
}
- (void)changeTitle:(NSNotification *)notice{
    
    if (notice.object) {
        
        self.albumModel.title = notice.object;
        
        [self setupNavTitle];
        
        PPPictureModel *coverPicM = self.albumHomeModel.ebookPictures[0];
        //    if (coverPicM.picType == 1) {
        self.albumHomeModel.CoverPicID = coverPicM.picID;
        self.albumHomeModel.coverURL = coverPicM.picURL;
        //    }
        
        self.templateM.coverFrameM.coverImgString = self.templateM.coverImgString;
        self.templateM.coverFrameM.coverModel = self.albumHomeModel;
        
        PPPhoto *coverPhoto = self.items[0];
        coverPhoto.picType = 1;
        self.albumHomeModel.title = notice.object;
        self.templateM.coverFrameM.coverModel = self.albumHomeModel;
        coverPhoto.coverFrame = self.templateM.coverFrameM;
        
        
    }
}
//切换缩略图 || 浏览大图
- (void)clickMore{
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:PPNotice_isEditImageChange object:nil];
    
    if ([self.currentVc isKindOfClass:[PPEbookPreviewCollectionViewController class]]) {
        
        [self addPreviewVc:[NSIndexPath indexPathForRow:0 inSection:0] photos:self.collectionVc.photos];
    }else{
        [self addCollectionVc];
    }
}
- (void)clickPlayMusic:(UIButton *)btn{

    btn.selected = !btn.isSelected;
    
    if (!btn.isSelected) {
        PPLog(@"停止");
        [self stop];
//        [self.playerLayer removeFromSuperlayer];
//        self.playerLayer=nil;
//        self.player=nil;
        
     [self.songBtn setImage:[UIImage imageNamed:@"song_pause"] forState:UIControlStateNormal];
    }else{
        
        [self.songBtn setImage:[UIImage imageNamed:@"song_play"] forState:UIControlStateNormal];
        PPLog(@"播放");
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSLog(@"mp3 path=%@",documentsDirectory);
        
        NSString *songPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL result = [fileManager fileExistsAtPath:songPath];
        if (result) {
            [self musicPlayerWithPath:songPath];
        }else{
            [self loadEbookMusic];
        }
    }
    
}
- (void)downTemplate:(id)sender{
    if (self.templateM.downloadType == PPTemplateDownLoadTypeFinish) {
        //使用模板
        [self.navigationController popViewControllerAnimated:NO];
        if (self.BlockEmployTemplate) {
            self.BlockEmployTemplate(self.templateM);
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];
        if (self.BlockDownLoadTemplate) {
            self.BlockDownLoadTemplate();
        }
    }
    
 
}
#pragma mark -电子书样式设置
- (void)reloadEbookData{

    //相册封面
    
    PPPhoto *coverPhoto = [[PPPhoto alloc] init];
    
    
    PPPictureModel *coverPicM = self.albumHomeModel.ebookPictures[0];
//    if (coverPicM.picType == 1) {
        self.albumHomeModel.CoverPicID = coverPicM.picID;
        self.albumHomeModel.coverURL = coverPicM.picURL;
//    }
    
    coverPhoto.picType = 1;
    self.templateM.coverFrameM.coverImgString = self.templateM.coverImgString;
    self.templateM.coverFrameM.coverModel = self.albumHomeModel;
    coverPhoto.coverFrame = self.templateM.coverFrameM;
    coverPhoto.style = PPPhotoCoverSytleCustom;
    [self.items addObject:coverPhoto];
    
    //相册描述
    if (self.albumHomeModel.title2.length > 0) {
        PPPhoto *descPhoto = [[PPPhoto alloc] init];
        descPhoto.picType = 3;
        descPhoto.descModel = self.templateM.descModel;
        descPhoto.lastStyle = PPPhotoLastCoverSytleCustom;
        descPhoto.descImg = self.albumHomeModel.eBookCoverImage;
        descPhoto.desc = self.albumHomeModel.title2;
        [self.items addObject:descPhoto];
    }
    
    //内页
    NSInteger index = 0;
    for (int i = 0; i<self.albumHomeModel.ebookPictures.count; i++) {
        
        PPPictureModel *picM = self.albumHomeModel.ebookPictures[i];
        if (picM.picType != 1) {
            index+=1;
            PPPhoto *photo = [[PPPhoto alloc] init];
            photo.picType = 2;
            photo.photoDesc =picM.picDesc;
            photo.bigImgUrl = picM.picURL;
            self.templateM.innerModel.desc = picM.picDesc;
            self.templateM.innerModel.page = i;
            self.templateM.innerModel.totalPage = self.albumHomeModel.pictures.count-1;
            picM.page = i;
            
            for (PPPictureModel *normalPic in self.albumHomeModel.pictures) {
                if ([normalPic.picID longValue] == [picM.picID longValue]) {
                    picM.picAuuid = normalPic.picAuuid;
                }
                
            }
            picM.albumAuuid = self.albumModel.auuid;
            picM.albumID = self.albumModel.albumID;
            self.templateM.innerModel.picModel = picM;
            photo.innerModel = self.templateM.innerModel;
            
            [photo.pics addObject:picM];
            [self.pics addObject:picM];
            [self.items addObject:photo];
//            [self.collectionImgs addObject:photo];
        }
    }
    
    
    
    NSInteger indexY = 0;
    for (int i = 0; i<self.albumHomeModel.pictures.count; i++) {
        
        PPPictureModel *picM = self.albumHomeModel.pictures[i];
        if (picM.picType != 1) {
            indexY+=1;
            PPPhoto *photo = [[PPPhoto alloc] init];
            photo.picType = 2;
            photo.photoDesc =picM.picDesc;
            photo.bigImgUrl = picM.picURL;
//            self.templateM.innerModel.desc = picM.picDesc;
//            self.templateM.innerModel.page = i;
//            self.templateM.innerModel.totalPage = self.albumHomeModel.pictures.count-1;
            picM.page = i;
            
            for (PPPictureModel *normalPic in self.albumHomeModel.pictures) {
                if ([normalPic.picID longValue] == [picM.picID longValue]) {
                    picM.picAuuid = normalPic.picAuuid;
                }
                
            }
//            picM.albumAuuid = self.albumModel.auuid;
//            picM.albumID = self.albumModel.albumID;
//            photo.innerModel = self.templateM.innerModel;
            
            [self.collectionImgs addObject:photo];
        }
    }
    
    
    //底图
    PPPhoto *lastPhoto = [[PPPhoto alloc] init];
    if (self.type == PPPhotoBrowserTypeEbook) {
        lastPhoto.orderNum = self.templateM.orderNum;
        lastPhoto.lastStyle =   PPPhotoLastCoverSytleCustom;
        [[SDImageCache sharedImageCache] queryDiskCacheForKey:self.templateM.url11 done:^(UIImage *image, SDImageCacheType cacheType) {
            lastPhoto.coverLastImage = image;
        }];
        [lastPhoto sd_setImageWithURL:[NSURL URLWithString:self.templateM.url11] placeholderImage:nil options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image) {
                lastPhoto.coverLastImage = image;
            }
        }];
    }
    [self.items addObject:lastPhoto];

    
    [self setupNavTitle];
    
    [self showBrowserView];
    
    /*
    //封面
    [self setupAlumCoverDesc];
    
    //内
    
    BOOL isCover = YES;
    PPHomeEbookModel *ebookM = [self.ebookAlbums firstObject];
    if (ebookM.picType !=1) {
        isCover = NO;
    }
    NSMutableArray *temp = [NSMutableArray array];
    for (int i = 0; i<self.ebookAlbums.count; i++) {
        
         PPHomeEbookModel *ebookM = self.ebookAlbums[i];
        
        if (ebookM.picType == 2) {
            [temp addObject:ebookM];
            PPPhoto *photo = [[PPPhoto alloc] init];
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];

            artwork.URLString = [NSString stringWithFormat:@"%@%@",PPPicHost,ebookM.url];
            self.templateM.innerModel.desc = ebookM.contentDescription;
            self.templateM.innerModel.page = isCover?i:(i + 1);
            self.templateM.innerModel.totalPage = self.ebookAlbums.count-1;
//            self.templateM.innerModel.sortedImages = sortedImages;
             self.templateM.innerModel.sortedImages = [temp copy];
//            self.templateM.innerModel.albumUUID = self.albumModel.auuid;
            self.templateM.innerModel.albumId = ebookM.albumId;
            self.templateM.innerModel.artwork = artwork;
//            self.templateM.innerModel.auuid = self.albumCoverModel.auuid;//
            photo.innerModel = self.templateM.innerModel;
            
            //    photo.flag = self.items.count;
            [self.items addObject:photo];
            photo.bigImgUrl = artwork.URLString;
            [self.collectionImgs addObject:photo];
        }

    }
    
    //底图
        PPPhoto *lastPhoto = [[PPPhoto alloc] init];
        if (self.type == PPPhotoBrowserTypeEbook) {
            lastPhoto.lastStyle =   ;
            [[SDImageCache sharedImageCache] queryDiskCacheForKey:self.templateM.url11 done:^(UIImage *image, SDImageCacheType cacheType) {
                lastPhoto.coverLastImage = image;
            }];
            [lastPhoto sd_setImageWithURL:[NSURL URLWithString:self.templateM.url11] placeholderImage:nil options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if (image) {
                    lastPhoto.coverLastImage = image;
                }
            }];
        }
      [self.items addObject:lastPhoto];
    
    
    [self setupNavTitle];
    
    [self showBrowserView];
*/
}
- (NSInteger)setupAlumCoverDesc{
/*
    //相册封面
    PPPhoto *coverPhoto = [[PPPhoto alloc] init];
    if (self.type == PPPhotoBrowserTypeAlbumNone) {
        coverPhoto.style = PPPhotoCoverSytleNone;
        //设置封面样式( 默认)
        coverPhoto.albumCoverModel = self.albumCoverModel;
        
    }else if(self.type == PPPhotoBrowserTypeEbook){
    
        coverPhoto.style = PPPhotoCoverSytleCustom;
        coverPhoto.coverFrame = self.templateM.coverFrameM;
 
    }
    
    [self.items addObject:coverPhoto];
    
    //相册描述
    if (self.albumCoverModel.title2.length > 0) {
//        PPPhoto *descPhoto = [PPPhoto photoViewWithText:self.albumCoverModel.title2];
        PPPhoto *descPhoto = [[PPPhoto alloc] init];
        
        if (self.type == PPPhotoBrowserTypeEbook) {
            descPhoto.descModel = self.templateM.descModel;
             descPhoto.lastStyle = PPPhotoLastCoverSytleCustom;
        }else{
            descPhoto.lastStyle = PPPhotoLastCoverSytleNone;
            descPhoto.backgroundColor = COLOR(0, 0,0, 0.9);
        }
        descPhoto.descImg = self.albumCoverModel.image;
        descPhoto.desc = self.albumCoverModel.title2;
        [self.items addObject:descPhoto];
    }
    */
    return self.items.count;
}

#pragma mark -显示默认相册样式
- (void)reloadData {
    //相册封面
    PPPhoto *coverPhoto = [[PPPhoto alloc] init];
    if (self.type == PPPhotoBrowserTypeAlbumNone) {
        coverPhoto.style = PPPhotoCoverSytleNone;
        //设置封面样式( 默认)
        coverPhoto.albumCoverModel = self.albumHomeModel;
    }
    [self.items addObject:coverPhoto];
    
    //相册描述
    if (self.albumHomeModel.title2.length > 0) {
        PPPhoto *descPhoto = [[PPPhoto alloc] init];
        if (self.type == PPPhotoBrowserTypeEbook) {
            descPhoto.descModel = self.templateM.descModel;
            descPhoto.lastStyle = PPPhotoLastCoverSytleCustom;
        }else{
            descPhoto.lastStyle = PPPhotoLastCoverSytleNone;
            descPhoto.backgroundColor = COLOR(0, 0,0, 0.9);
        }
        descPhoto.descImg = self.albumHomeModel.coverImage;
        descPhoto.desc = self.albumHomeModel.title2;
        [self.items addObject:descPhoto];
    }
    
    
    for (int i = 0; i<self.albumHomeModel.pictures.count; i++) {
        
        PPPictureModel *picM = self.albumHomeModel.pictures[i];
        if (picM.picType != 1) {
            PPPhoto *photo = [[PPPhoto alloc] init];
            photo.photoDesc =picM.picDesc;
            photo.bigImgUrl = picM.picURL;
            [self.items addObject:photo];
            [self.collectionImgs addObject:photo];
        }
        
    }
    
    
    PPPhoto *lastPhoto = [[PPPhoto alloc] init];
        lastPhoto.lastStyle = PPPhotoLastCoverSytleNone;
        //封面 + 二维码
        lastPhoto.coverLastImage = self.albumHomeModel.coverImage;
    [self.items addObject:lastPhoto];

    [self setupNavTitle];
        
    [self showBrowserView];

    
/*
    NSArray <PPAlbumImageModel *> *images = [PPAlbumImageModel where:@{@"auuid" : self.albumModel.auuid, @"deleted" : @(NO)}];
    
    NSArray *sortedImages = nil;
    if(self.albumModel.order.integerValue == PPAlbumOrderDesc) {
        sortedImages = images;
    } else {
        sortedImages = [images.reverseObjectEnumerator allObjects];
    }

    //获取封面和描述信息
   [self setupAlumCoverDesc];
    
    [sortedImages enumerateObjectsUsingBlock:^(PPAlbumImageModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        PPAbstractArtwork *artwork = obj.artwork;
        
//        PPImageFlowItem *item = [[PPImageFlowItem alloc] init];
//        item.image = artwork.image;
//        item.URLString = artwork.URLString;
//        item.representedObject = artwork;
//        [items addObject:item];
        
//        NSMutableArray *photos = [NSMutableArray array];
            
//            UIImageView *child = artwork.image;
            PPPhoto *photo = [[PPPhoto alloc] init];
            //1.1设置原始imageView
//            photo.sourceImageView = child;
            //1.2设置大图URL
//            photo.bigImgUrl = artwork.URLString;
            //1.3设置图片tag
//            photo.tag = i;
    
        if (self.innerImageURLs.count == sortedImages.count && self.innerImageURLs.count > 0   ) {
//            photo.bigImgUrl = self.innerImageURLs[idx];
            PPLog(@"进来了%@",self.innerImageURLs[idx]);
            artwork.URLString = [NSString stringWithFormat:@"%@%@",PPPicHost,self.innerImageURLs[idx]];
        }else{
            photo.bigImgUrl = artwork.URLString;
        }
        
        if (self.type == PPPhotoBrowserTypeEbook) {
//            self.templateM.innerModel.url =  artwork.URLString;
            self.templateM.innerModel.desc = artwork.desc;
            self.templateM.innerModel.page = idx + 1;
            self.templateM.innerModel.totalPage = sortedImages.count;
            self.templateM.innerModel.sortedImages = sortedImages;
            self.templateM.innerModel.albumUUID = self.albumModel.auuid;
            self.templateM.innerModel.artwork = artwork;
            photo.innerModel = self.templateM.innerModel;
        }else{
            photo.photoDesc =artwork.desc;
        
        }
        photo.flag = self.items.count;
        [self.items addObject:photo];
        
        [self.collectionImgs addObject:photo];
    }];
    

    //底图
    if (self.type == PPPhotoBrowserTypeAlbumNone || self.type == PPPhotoBrowserTypeEbook) {
        PPPhoto *photo = [[PPPhoto alloc] init];

        if (self.type == PPPhotoBrowserTypeEbook) {
            photo.lastStyle = PPPhotoLastCoverSytleCustom;
            [[SDImageCache sharedImageCache] queryDiskCacheForKey:self.templateM.url11 done:^(UIImage *image, SDImageCacheType cacheType) {
                 photo.coverLastImage = image;
            }];
            
            [photo sd_setImageWithURL:[NSURL URLWithString:self.templateM.url11] placeholderImage:nil options:SDWebImageRetryFailed | SDWebImageLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
            } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {   
                if (image) {
                    photo.coverLastImage = image;
                }
            }];

            
        }else{
            photo.lastStyle = PPPhotoLastCoverSytleNone;
            //封面 + 二维码
            photo.coverLastImage = self.albumCoverModel.image;
        }
        [self.items addObject:photo];
        
        [self setupNavTitle];

    }else{
    
    }
    [self showBrowserView];
    
    */
}
- (void)setupNavTitle{

    //设置导航标题
//    self.navBarPreview.topLabel.text = self.albumModel.title;
//    self.navBarPreview.bottomLabel.text = [NSString stringWithFormat:@"1/%zd",self.items.count];
//    self.navigationItem.titleView = self.navBarPreview;
    
    self.title = self.albumModel.title;
}
- (void)showBrowserView{
    
    self.previewVc.isPreviewFullScreen = (self.type == PPPhotoBrowserTypeTemplate || self.type == PPPhotoBrowserTypeEbook||self.type == PPPhotoBrowserTypeAlbumNone);
    self.previewVc.changeSize = (self.type == PPPhotoBrowserTypeEbook);
    self.previewVc.pictures = self.pics;
    self.previewVc.photos = self.items;
    self.previewVc.currentIndex = 0;
    self.previewVc.normalStyle = self.type == PPPhotoBrowserTypeAlbumNone;
    if (self.templateM.orderNum == 0) {
        self.previewVc.normalStyle = YES;
    }
    [self addChildViewController:self.previewVc];
    self.previewVc.view.bounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:self.previewVc.view];
    [self addChildViewController:self.collectionVc];
}
- (void)ebookPreviewViewControllerTabView:(PPPhoto *)view{

    self.isHidden = !self.isHidden;
    [[UIApplication sharedApplication] setStatusBarHidden:self.isHidden];
    [self.navigationController setNavigationBarHidden:self.isHidden animated:TRUE];
}
- (void)ebookPreviewCollectionView:(UICollectionView *)collectionview didSelIndex:(NSIndexPath *)indexPath photos:(NSMutableArray *)photos{
    
    [self addPreviewVc:indexPath photos:photos];
}
- (void)ebookPreviewScrollViewDidScrollIndex:(NSInteger)index{
    
    self.moreBtn.hidden = NO;
    self.songBtn.hidden = NO;
    self.previousSelectIndex = index;
    
    self.navBarPreview.bottomLabel.text = [NSString stringWithFormat:@"%zd/%zd",index+1,self.items.count];
}
- (void)addCollectionVc{

    self.moreBtn.hidden = YES;
    self.songBtn.hidden = YES;
    
    if (self.collectionVc == nil) {
        [self addChildViewController:self.collectionVc];
    }

//    self.collectionVc.photos = self.previewVc.photos;

    
    self.collectionVc.photos = self.collectionImgs;
    
    [self.previewVc.view removeFromSuperview];
    [self.previewVc removeFromParentViewController];
    self.previewVc = nil;
    
    self.collectionVc.view.frame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height);
    [self.view addSubview:self.collectionVc.view];
    self.currentVc = self.collectionVc;
    
//    self.titleLabel.text = self.albumModel.title;
//    self.navigationItem.titleView = self.titleLabel;
    self.title = self.albumModel.title;
    self.navigationItem.rightBarButtonItem = nil;
    
}

- (void)addPreviewVc:(NSIndexPath *)indexPath photos:(NSMutableArray *)photos{

    self.moreBtn.hidden = NO;
    self.songBtn.hidden = NO;
    if (self.previewVc == nil) {
        self.previewVc.changeSize = (self.type == PPPhotoBrowserTypeEbook);
        [self addChildViewController:self.previewVc];
    }

    self.previewVc.photos = self.items;
    self.previewVc.isPreviewFullScreen = (self.type == PPPhotoBrowserTypeTemplate || self.type == PPPhotoBrowserTypeEbook||self.type == PPPhotoBrowserTypeAlbumNone);
    
    NSInteger index = indexPath.item;
    self.previewVc.changeSize = (self.type == PPPhotoBrowserTypeEbook);
    
    index += (self.items.count - self.collectionImgs.count);
    self.previewVc.currentIndex = index-1;
    self.previewVc.pictures = self.pics;
    self.previousSelectIndex = self.previewVc.currentIndex;
    self.previewVc.normalStyle = self.type == PPPhotoBrowserTypeAlbumNone;
    if (self.templateM.orderNum == 0) {
        self.previewVc.normalStyle = YES;
    }
    [self.collectionVc.view removeFromSuperview];
    [self.collectionVc removeFromParentViewController];
    
    self.previewVc.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.view addSubview:self.previewVc.view];
    self.currentVc = self.previewVc;
    
//    self.navBarPreview.topLabel.text = self.albumModel.title;
//    self.navBarPreview.bottomLabel.text = [NSString stringWithFormat:@"%zd/%zd",index+1,self.items.count];
//    self.navigationItem.titleView = self.navBarPreview;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_more"] style:UIBarButtonItemStylePlain target:self action:@selector(clickMore)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"音乐" style:UIBarButtonItemStyleDone target:self action:@selector(goMusicList)];
    self.navigationItem.rightBarButtonItem.tintColor = BLACK;
    
    [self.previewVc showPhotoDescIndex:index];
    
}

#pragma mark -加载音乐
- (void)loadEbookMusic{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"mp3 path=%@",documentsDirectory);
    NSString *songPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:songPath];
    if (result) {
        NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
        PPLog(@"播放地址 = %@",fullPath);
        [self musicPlayerWithPath:fullPath];
        
        return;
    }
    
    
    [PPNetworkService musicEbookWithparams:@{@"albumid":self.albumHomeModel.albumID} callback:^(id data, NSError *error) {
        PPLog(@"电子书音乐---%@ -- %@",data,error);
        if (error == nil) {
            JCDownloadItem *downloadItem = [[JCDownloadItem alloc] init];
            NSString *musicURL = data[@"url"];
            if (musicURL.length <= 0) {
                //                self.songBtn.selected = NO;
//                musicURL = @"http://imgtest.pickpic.cc/llr3nOSc2Dh3IFC6ERcYae5QYnWd";
                
//                [self.songBtn removeFromSuperview];
//
//                self.songBtn = nil;
//
//                 return ;
//
//                //如果是默认的电子书且没查到 就播放默认音乐
                if (self.templateM.orderNum == 0) {
                    
                    self.songBtn.selected = NO;
                    musicURL = @"http://imgtest.pickpic.cc/llr3nOSc2Dh3IFC6ERcYae5QYnWd";
                }else{
                    
                    [self.songBtn removeFromSuperview];
                    
                    self.songBtn = nil;
                    
                    return ;
                    
                }
                
            }
            
            if (![musicURL isValid]) {
                musicURL = self.templateM.musicUrl;
            }

                                  
            downloadItem.downloadUrl = musicURL;
            downloadItem.downloadFilePath = songPath;
            self.operation = [JCDownloadOperation operationWithItem:downloadItem];
            [self.operation startWithProgressBlock:^(NSProgress *progress) {
                
                //update progress
            } completionBlock:^(NSURL *filePath, NSError *error) {
                //download operation completion, do something
                
                NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,[NSString stringWithFormat:@"%@.mp3",self.albumHomeModel.albumID]];
                
                PPLog(@"播放地址 = %@",fullPath);
                [self musicPlayerWithPath:fullPath];
            }];
        }else{
            self.songBtn.enabled = YES;
            [self.navigationController.view toastMessage:@"音乐加载失败,请点击重新播放"];

        }
    }];
}

#pragma mark 播放
- (void)musicPlayerWithPath:(NSString *)path{
    
    self.songBtn.enabled = YES;
    NSURL *videoURL = [NSURL fileURLWithPath:path];
    
    NSError *err;
    self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:videoURL error:&err];
    
    PPLog(@"%@",[err description]);
    
//    self.audioPlayer.delegate = self;
    
//    [self.audioPlayer setNumberOfLoops:MAXINTERP];
    [self.audioPlayer setNumberOfLoops:MAXINTERP];
    
    [self.audioPlayer play];
    [_songBtn setImage:[UIImage imageNamed:@"song_play"] forState:UIControlStateNormal];
    [self rotate];
 
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(rotateUpdate) userInfo:nil repeats:YES];
    }
}
- (void)rotateUpdate{
//    [self rotate];
}



- (void)start:(UIButton *)sender{
    
    if ([self.audioPlayer isPlaying]) {
//        [self.startBtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:0];
        
        [self.audioPlayer pause];
    }
    else
    {
//        [self.startBtn setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:0];
        [self.audioPlayer play];
    }
    
//    if (_timer == nil) {
//        _timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
//    }
}
- (void)stop{
    
    [self.audioPlayer stop];
    
    self.audioPlayer = nil;
    
    //计时器停止
    [_timer invalidate];
    //释放定时器
    _timer = nil;
    
    [self.songBtn.imageView.layer removeAllAnimations];
    
}
-(void)updateProgress{
    //进度条显示播放进度
//    self.progress.progress = self.player.currentTime/self.player.duration;
//    self.info1.text = [NSString stringWithFormat:@"当前播放时间%f",self.player.currentTime];
}
-(void)rotate{
    CABasicAnimation * rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; //让其在z轴旋转
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 4.0 ];//旋转角度
    rotationAnimation.duration = 5; //旋转周期
    rotationAnimation.cumulative = YES;//旋转累加角度
    rotationAnimation.repeatCount = MAXINTERP;//旋转次数
    [self.songBtn.imageView.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    
}
@end
